<?php

/**
 * 金额转换：分转换为元.
 *
 * @param int  $fen
 * @param bool $withThousandsSeparator
 *
 * @return string
 */
function toYuan($fen, $withThousandsSeparator = false)
{
    $thousandsSep = $withThousandsSeparator ? ',' : '';

    return number_format($fen / 100, 2, '.', $thousandsSep);
}

/**
 * 金额转换：元转换为分.
 *
 * @param string $yuan
 *
 * @return int
 */
function toFen($yuan)
{
    // 替换千分符
    $yuan = str_replace(',', '', $yuan);

    return intval(strval($yuan * 100));
}

/**
 * 格式化金额.
 */
function formatPrice(string $value): string
{
    return sprintf('%.2f', $value);
}

/**
 * 除法计算(处理分母为0的情况).
 *
 * @param $numerator
 * @param $denominator
 * @param $precision
 * @param int $defaultValue
 *
 * @return float|int
 */
function safe_divide($numerator, $denominator, $precision = null, $defaultValue = 0)
{
    if (0 == $numerator) {
        return 0;
    }
    if (0 == $denominator) {
        return $defaultValue;
    }

    $divideResult = $numerator / $denominator;
    if ($precision) {
        return round($divideResult, $precision);
    }

    return $divideResult;
}

function hide_mobile($mobile)
{
    return Str::substr($mobile, 0, 3) . '****' . Str::substr($mobile, 7, 4);
}

function drop_special_char($str)
{
    $length = mb_strlen($str);
    $array = [];
    $tmp = '';
    for ($i = 0; $i < $length; ++$i) {
        $array[] = mb_substr($str, $i, 1, 'utf-8');
        if (strlen($array[$i]) >= 4) {
            continue;
        }
        $tmp .= $array[$i];
    }

    return $tmp;
}

function encrypt_rsa($data, $publicKey)
{
    openssl_public_encrypt($data, $encrypted, $publicKey);

    return base64_encode($encrypted);
}

function encrypt_aes($data, $key)
{
    $cipher = 'AES-128-ECB';
    $encrypted = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA);

    return base64_encode($encrypted);
}
